package com.b2c.ftysys.sevice.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.create.NewCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.b2c.ftysys.dao.B2cFsyWipDAO;
import com.b2c.ftysys.dao.DatabaseException;
import com.b2c.ftysys.domain.B2cFsyWip;
import com.b2c.ftysys.domain.B2cFsyWipExample;
import com.b2c.ftysys.domain.ExampleFactory;
import com.b2c.ftysys.domain.FtyWip;
import com.b2c.ftysys.domain.FtyWipExample;
import com.b2c.ftysys.domain.PageResult;
import com.b2c.ftysys.sevice.ProductService;
import com.b2c.ftysys.sevice.RouteService;
import com.b2c.ftysys.sevice.ServicesException;
import com.b2c.ftysys.sevice.WipService;

@Service
@RemoteProxy(creator = NewCreator.class, name = "wipService")
public class WipServiceImpl implements WipService {

	/**
	 * order wip 缓存, key为工厂Sku, value为FtyWip对象
	 */
	private static Map<String, FtyWip> wipCache = new HashMap<String, FtyWip>();

	@Autowired
	private B2cFsyWipDAO dao;

	@Autowired
	private ProductService productService;

	@Autowired
	RouteService routeService;

	public B2cFsyWipDAO getDao() {
		return dao;
	}

	public void setDao(B2cFsyWipDAO dao) {
		this.dao = dao;
	}

	public void clearAllCache() {
		wipCache.clear();
	}
	
	
//	public void updateCacheByEntry(FtyWip wip){
//		if (null == wip || StringUtils.isEmpty(wip.getPdtSkuId()))
//			return;
//		if (wipCache.containsKey(wip.getPdtSkuId())) {
//			removeByKey(wip.getPdtSkuId());
//			wipCache.put(wip.getPdtSkuId(), wip);
//		} else
//			wipCache.put(wip.getPdtSkuId(), wip);
//	}

	public FtyWip getByKey(String key) {
		if (StringUtils.isEmpty(key))
			return null;
		return wipCache.get(key);
	}

	public FtyWip getByEntry(FtyWip wip) {
		if (null == wip || StringUtils.isEmpty(wip.getPdtSkuId()))
			return null;
		return wipCache.get(wip.getPdtSkuId());
	}

	public void putInCache(FtyWip wip) {
		if (null == wip || StringUtils.isEmpty(wip.getPdtSkuId()))
			return;

		if (wipCache.containsKey(wip.getPdtSkuId())) {
			removeByKey(wip.getPdtSkuId());
			wipCache.put(wip.getPdtSkuId(), wip);
		} else
			wipCache.put(wip.getPdtSkuId(), wip);
	}

	public void putInCache(List<FtyWip> wips) {
		if (null == wips || wips.size() <= 0)
			return;
		for (FtyWip wip : wips) {
			this.putInCache(wip);
		}
	}

	public void removeByKey(String key) {
		if (StringUtils.isEmpty(key))
			return;
		wipCache.remove(key);
	}

	public void removeByEntry(FtyWip wip) {
		if (null == wip || StringUtils.isEmpty(wip.getPdtSkuId()))
			return;
		wipCache.remove(wip.getPdtSkuId());
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getWipByProSku(String proSku) {
		try {
			return dao.getSqlClient().queryForList(
					"b2c_fsy_wip.abatorgenerated_selectBySku_Map", proSku);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public PageResult getWipByPage(PageResult page) throws ServicesException {
		page
				.setSelectDataMappedId("b2c_fsy_wip.selectOrderFtyProductByExample");
		page.setCountMappedId("b2c_fsy_wip.countOrderFtyProductByExample");
		try {
			return this.dao.getListByPage(page);
		} catch (DatabaseException e) {
			e.printStackTrace();
			throw new ServicesException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public FtyWip getWipBySkuId(String sku) {
		if (null != this.getByKey(sku)) {// 查找缓存
			return this.getByKey(sku);
		}

		FtyWipExample example = ExampleFactory.createFtyWipExample();
		example.createCriteria().andPdtskuidEqualTo(sku);

		List<FtyWip> dataList;
		try {
			dataList = this.dao.getSqlClient().queryForList(
					"b2c_fsy_wip.selectOrderFtyProductByExample", example);
			if (null == dataList || dataList.size() <= 0)
				return null;
			this.putInCache(dataList.get(0));
			return dataList.get(0);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int regWip(B2cFsyWip wip, String routeId) {
		B2cFsyWipExample example = ExampleFactory.createWipExample();
		example.createCriteria().andProSkuEqualTo(wip.getProSku())
				.andWsIdEqualTo(wip.getWsId());
		productService.regRoute(wip.getProSku(), routeId);
		int ws_now = routeService.getFtySkuNowWsId(wip.getProSku());
		if (ws_now == -1) {// 已执行完
			productService.makeUp(wip.getProSku());
			makeUpLastWipTime(wip.getProSku());
			return ws_now;
		}
		if (wip.getWsId() == ws_now) {
			if (dao.countByExample(example) > 0)
				return 0;
			makeUpProvWipTime(wip.getProSku());
			dao.save(wip);
			if (routeService.isLastWsId(wip.getProSku(), wip.getWsId())) {
				makeUpLastWipTime(wip.getProSku());
				productService.makeUp(wip.getProSku());
			}
		} else
			return 0;
		return 1;
	}

	public void makeUpLastWipTime(String sku) {
		B2cFsyWip wip = new B2cFsyWip();
		int wipId = routeService.getLastWipId(sku);
		if (wipId > 0) {
			wip.setWipId(wipId);
			wip.setEndTime(new Date());
			updateWip(wip);
		}
	}

	public void makeUpProvWipTime(String sku) {
		B2cFsyWip wip = new B2cFsyWip();
		int wipId = routeService.getFtySkuPrevWipId(sku);
		if (wipId > 0) {
			wip.setWipId(wipId);
			wip.setEndTime(new Date());
			updateWip(wip);
		}
	}

	public int updateWip(B2cFsyWip wip) {
		return dao.updateByPrimaryKeySelective(wip);
	}

	@SuppressWarnings("unchecked")
	public String getSuggestRouteType(String styleNo) {
		String suggest = "";
		try {
			List<String> routes = this.dao.getSqlClient().queryForList(
					"getSuggestRouteType", styleNo);
			if (null == routes || routes.size() <= 0)
				return suggest;

			boolean first = true;
			for (String string : routes) {
				if (first) {
					suggest += string;
					first = false;
				} else {
					suggest += "," + string;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return suggest;
	}

}
